package com.aqie.medium.hash;

import java.util.HashMap;

/**
 * 36 有效的数独  todo
 */
public class IsValidSudoku {
    /**
     * 枚举子数独：index = (row / 3) * 3 + column / 3
     * 行、列、子数独没重复项：value->count 哈希映射
     * @param board
     * @return
     */
    public boolean isValidSudoku(char[][] board) {
        // init data
        HashMap<Integer, Integer>[] rows = new HashMap[9];
        HashMap<Integer, Integer> [] columns = new HashMap[9];
        HashMap<Integer, Integer> [] boxes = new HashMap[9];
        for (int i = 0; i < 9; i++) {
            rows[i] = new HashMap<Integer, Integer>();
            columns[i] = new HashMap<Integer, Integer>();
            boxes[i] = new HashMap<Integer, Integer>();
        }

        // validate a board
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char num = board[i][j];
                if (num != '.') {
                    int n = (int)num;
                    int box_index = (i / 3 ) * 3 + j / 3;

                    // keep the current cell value
                    rows[i].put(n, rows[i].getOrDefault(n, 0) + 1);
                    columns[j].put(n, columns[j].getOrDefault(n, 0) + 1);
                    boxes[box_index].put(n, boxes[box_index].getOrDefault(n, 0) + 1);

                    // check if this value has been already seen before
                    if (rows[i].get(n) > 1 || columns[j].get(n) > 1 || boxes[box_index].get(n) > 1)
                        return false;
                }
            }
        }

        return true;
    }


    public boolean isValidSudoku2(char[][] board) {
        for(int i=0;i<9;i++) {
            if(!check(board[i])) {
                return false;
            }

        }
        for(int i=0;i<9;i++) {
            char[] t = new char[9];
            for(int j=0;j<9;j++) {
                t[j]=board[j][i];
            }
            if(!check(t)) {
                return false;
            }

        }
        for(int i=0;i<9;i+=3) {
            for(int j=0;j<9;j+=3) {
                char[] t = new char[9];
                int index = 0;
                for(int k=0;k<3;k++) {
                    for(int w=0;w<3;w++) {
                        t[index++] = board[i+k][j+w];
                    }
                }
                //System.out.println(t);
                if(!check(t)) {
                    return false;
                }
            }
        }
        return true;
    }

    private boolean check(char[] a) {
        int[] tmp = new int[10];
        for(int i=0;i<9;i++) {
            if(a[i]!='.') {
                tmp[a[i]-'0']++;
                if(tmp[a[i]-'0']>1) {
                    return false;
                }
            }
        }
        return true;
    }

}
